# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: server\http_responses\base.py
__author__ = "sanyi"
from types import GeneratorType


class BaseResponse:
    def __init__(
        self,
        body,
        headers=None,
        response_status="200 OK",
        cookie=None,
        disable_cache=True,
    ):
        """
        :param body:
        :param headers:
        :param response_status:
        :param cookie: a cookie string or list of cookies
        :return:
        """
        self.response_status = response_status
        self.body = body
        self._headers = headers if headers else dict()
        if disable_cache:
            self._headers["Pragma"] = "no-cache"
            self._headers["Expires"] = "-1"
            self._headers["Cache-Control"] = "no-cache, must-revalidate"
        self.cookie = cookie

    @property
    def headers(self):
        headers = list(self._headers.items())
        if self.cookie:
            if isinstance(self.cookie, (list, tuple)):
                for c in self.cookie:
                    headers.append(("Set-Cookie", c))

            else:
                headers.append(("Set-Cookie", self.cookie))
            return headers

    def __call__(self):
        if isinstance(self.body, str):
            yield self.body.encode("utf-8")
        else:
            if isinstance(self.body, GeneratorType):
                yield from self.body
            else:
                yield self.body

    def __str__(self):
        result = "HTTP-RESPONSE:" + self.response_status + "\r\n"
        for header in self._headers.items():
            result += "%s: %s\r\n" % header

        result += "\r\n\r\n"
        if isinstance(self.body, str):
            result += self.body
        else:
            if isinstance(self.body, bytes):
                result += self.body.decode("utf-8")
            else:
                result += str(self.body)
            return result

    def __repr__(self):
        return self.__str__()
